package com.cn.common;

import com.cn.msg.Message;
import com.cn.msg.ProxyMessage;
import com.cn.util.SerializationUtil;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class RemoteCommand {

    public static ByteBuffer encode(Message msg) {
        int length = 4;
        length = length + 1;//flag
        length = length + 1;//type
        byte[] bytes = new byte[2];
        bytes[0] = msg.getType();
        bytes[1] = msg.getFlag();

        ByteBuffer result = ByteBuffer.allocate(length);
        result.putInt(length);//4位
        result.put(bytes);//2位
        result.flip();

        return result;
    }

    public static Message decode(ByteBuffer byteBuffer) {
        int limit = byteBuffer.limit();
        int length = byteBuffer.getInt();
        byte[] bytes = new byte[length - 4];
        byteBuffer.get(bytes);
        Message message = new Message();
        message.setType(bytes[0]).setFlag(bytes[1]);

        System.out.println("limit：" + limit + " length：" + length + " type：" + message.getType() + "===" + message.getFlag());


        return message;
    }

    public static void main(String[] args) {
        String body = "hi,姚进";
        Message message = new Message();
        message.setFlag((byte) 0x1).setType((byte) 0x1).setByteBodys(body.getBytes(Charset.forName("utf-8")));
        ByteBuffer bytes = encode(message);
        System.out.println(bytes.limit() + "===");
        decode(bytes);
    }

}
